package com.njsf.utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class ValidateCode {

    public static void validateCode(HttpServletRequest request,HttpServletResponse response) throws IOException {

        int WIDTH = 60;
        int HEIGHT = 30;
        //验证码字符集
        String chars = "abcdefghijklmnopqrstuvwxyz0123456789";

        Random random = new Random();
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(randomColor(random));
        graphics.fillRect(0,0,WIDTH,HEIGHT);

        for(int i=0;i<20;i++){
            graphics.setColor(randomColor(random));
            graphics.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(WIDTH),random.nextInt(HEIGHT));
        }

        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0;i<4;i++){
            int index = random.nextInt(chars.length() - 1);
            stringBuffer.append(chars.substring(index,index+1));
        }
<<<<<<< HEAD
        request.getSession().setAttribute("validatecode",stringBuffer.toString());
=======

        request.getSession().setAttribute("validateCode",stringBuffer);

>>>>>>> 180ace60693232df69575b4f82fc34aeb3fc90e8
        graphics.setColor(new Color(255,255,255));
        graphics.setFont(new Font("宋体",Font.BOLD,18));
        int strW = graphics.getFontMetrics().stringWidth(stringBuffer.toString());
        int strH = graphics.getFontMetrics().getHeight();
        int ascent = graphics.getFontMetrics().getAscent();
        System.out.println(strW);
        System.out.println(strH);
        graphics.drawString(stringBuffer.toString(),(WIDTH-strW)/2,(HEIGHT-strH)/2+ascent);
        graphics.dispose();
        OutputStream os = response.getOutputStream();
        ImageIO.write(image,"jpeg",os);
        os.flush();
        os.close();

    }


    public static Color randomColor(Random random){
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r,g,b);
    }

}
